<template>
  <div>
    <base-modal
      class="material-list-dialog-container"
      :show.sync="visible"
      :title="title"
      width="900px"
      @closed="reset"
      append-to-body
    >
      <div class="search-box">
        <el-input 
          :placeholder="$t('common.form.preview.materialVerifyEliminate.placeholder1')" 
          prefix-icon="el-icon-search" 
          v-model="keyWord"
          @input="search"
        >
        </el-input>
      </div>
      <div class="table-box">
        <material-table-new-version ref="materialTableNewVersion" :data="copyData" :ruleOptions="ruleOptions" :isShowSettlementRules="isShowSettlementRules" :field="field" :border="true" :isShowSettleType="isShowSettleType" />
      </div>
      <div class="paging-box">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          @current-change="handlePageChange"
        >
        </el-pagination>
      </div>


      <div class="dialog-footer" slot="footer">
        <el-button :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :disabled="pending" @click="submit">{{$t('common.base.submit')}}</el-button>
      </div>
      <!-- end 出库方式 -->
    </base-modal>

  </div>
</template>

<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';

/* components */
import MaterialTableNewVersion from './MaterialTableNewVersion.vue';
import _ from 'lodash'
import i18n from '@src/locales'

import { getCustomerArrdess } from '@src/filter/fmt.js';

import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
import { handlerMaterialList } from '@src/modules/task/view/components/materialUtil.js';

export default {
  name: 'material-list-dialog',
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    card: {
      type: Object,
      default: () => ({})
    },
    taskId: {
      type: String,
      default: ''
    },
    task: {
      type: Object,
      default: () => ({})
    },
    templateId: {
      type: String,
      default: ''
    },
    // 已选中数据
    value: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    ruleOptions: {
      type: Array,
      default: () => ([])
    },
    // 是否需要被填写申请物料
    showReplacedMaterialCheck:{
      type:Boolean,
      default:false
    },
    // 规则灰度
    isShowSettlementRules: {
      type: Boolean,
      default: false
    },
    isShowSettleType: {
      type: Boolean,
      default: false
    },
    // 产品质保的状态
    serviceQualityStatus: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pending: false,
      visible: false,
      // 完成出库的物料信息
      data: [],
      params: {},
      disabled: false,
      total:0,
      keyWord: '',
      copyData:[],
      pageSize:5,
      pageNum:1,
      title: i18n.t('common.form.preview.materialVerifyEliminate.btn1'),
      internationalGray: false
    }
  },
  computed: {
    /** 物料清单附加组件配置 */
    cardConfig() {
      return JSON.parse(this.card.config || '{}');
    }
  },
  mounted() {
    const { internationalGray } = useFormMultiLanguage()
    this.internationalGray = internationalGray
  },
  methods: {
    // 搜索
    search() {
      // 根据keyword 对静态 data 数据进行筛选 
      let data = this.data;
      let keyWord = this.keyWord;
      if (keyWord) {
        data = data.filter(item => {
          return item.materialName.indexOf(keyWord) > -1 || item.materialSn.indexOf(keyWord) > -1
        });
      }
      if(data.length){
        this.copyData = _.cloneDeep(data.slice(0, 5))
        this.total = data.length
      }else{
        this.copyData = []
        this.total = 0
      }
    },
    // 页数改变
    handlePageChange(val) {
      this.pageNum = val
      if(this.type){
        this.getPersonalWarehouseList()
      }else{
        // 前端通过val对数据进行分页
        this.copyData = this.data.slice((val - 1) * this.pageSize, val * this.pageSize);
      }
    },
    /**
    * @description 打开弹窗
    */
    open(type) {
      this.data = []
      this.copyData = []
      this.$refs?.materialTableNewVersion?.outsideSetTableData()
      if(!type){
        this.title = this.$t('common.form.preview.materialVerifyEliminate.btn1')
        this.getTaskListMaterial()
      }else if(type === 'personalLibrary'){
        this.title = this.$t('common.form.preview.materialVerifyEliminate.btn2')
        this.getPersonalWarehouseList(type)
      }
      this.type = type
      this.pending = false
      this.visible = true
    },
    /**
    * @description 获取已出库的物料清单
    */
    getTaskListMaterial(){
      let params = {
        taskId: this.task?.id || '',
        needAreaPrice: this.field?.setting?.useRegionalPricing || false,
        address: getCustomerArrdess(this.task)
      }
      WareHouseApi.getOutWarehouseMaterialFinished(params).then(res=>{
        if(res.success){
          let dataList = res.result || []
          const parentTableData = this.$parent.tableValue || []
          let materialData = dataList.map(item => {
            parentTableData.length && parentTableData.forEach(val => {
              let materialId = val.materialId ?? val.primaryId
              let warehousePositionId = val.warehousePositionId ?? val.positionId
              if(Number(materialId) === item.materialId && val.warehouseId === item.warehouseId && Number(warehousePositionId) === item.warehousePositionId){
                item.num = item.num - val.number
              }
            })
            item.number = 0
            item.availableNum = item.num // 统一可用库存字段名
            item.positionId = item.warehousePositionId
            item.snList = item.snList || [] 
            item.settlementRulesId = '' // 结算规则
            return item
          })
          this.data = handlerMaterialList(materialData, this.columns)
          
          if(this.data.length){
            this.copyData = _.cloneDeep(this.data.slice(0, 5))
            this.total = this.data.length
          }else{
            this.copyData = []
            this.total = 0
          }
        }
      })
    },
    // 获取个人库的仓库信息
    getPersonalWarehouseList() {
      // 个人库数据
      WareHouseApi.getPersonalInventoryWarehouse()
        .then((result) => {
          
          if (result?.success) {
            let warehouse = result?.data.warehouse || {}
            this.getWarehousePersonData(warehouse.id)
          }
          
        }).catch(error => {
          console.error(error);
        })
    },
    /**
    * @description 获取个人库和仓库的物料清单
    */
    getWarehousePersonData(id){
      let params = {
        keyword: this.keyWord,
        pageNum:this.pageNum,
        pageSize:this.pageSize,
        warehouseId:id,
        personWarehouse: this.type === 'personalLibrary' ? true : false,
        needAreaPrice: this.field?.setting?.useRegionalPricing || false,
        address: getCustomerArrdess(this.task)
      }
      WareHouseApi.getWarehousePersonDataApi(params).then(res=>{
        if(res.success){
          let dataList = handlerMaterialList((res.result?.list || []), this.columns)

          let materialData = dataList.map(item => {
            item.number = 1
            item.availableNum = item.num // 统一可用库存字段名
            item.positionId = item.warehousePositionId
            item.snList = item.snList || [] 
            item.settlementRulesId = '' // 结算规则
            // 没有物料质保状态，就取产品的质保状态
            item.warrantyStatus = item.warrantyStatus ? item.warrantyStatus : this.serviceQualityStatus
            // 是否个人库
            item.isPerson = item?.isPerson ?? false
            return item
          })

          this.data = materialData
          this.total = res.result.total 
          if(this.data.length){
            this.copyData = _.cloneDeep(this.data)
          }else{
            this.copyData = []
          }
        }
      })
    },
    /**
    * @description 提交
    * @param {Object} formParams 添加物料
    */
    async submit() {
      let tableData = this.getTableData()
      tableData = tableData.length && tableData.filter(item => item.number)
      if (!tableData.length) return this.$message.warning(this.$t('common.form.preview.materialVerifyEliminate.tip1'))

      if (this.isShowSettlementRules) {
        // 选中的数据只要有一个没有勾选规则就提示
        const isPass = tableData.some(item => item?.settlementRulesId?.toString().length <= 0)
        if(isPass) {
          return this.$message.warning(this.$t('zhongqi.tipList.tips2'))
        }
      }
      if(this.internationalGray) {
        tableData = tableData.map(item=> {
          return {
            ...item,
            salePriceCurrency: item.salePriceCurrency || 'CNY'
          }
        })
      }

      // 开启配件结算方式 则必填
      if (this.isShowSettleType) {
        const isExist = tableData.some(item => !item?.settleType)
        if (isExist) return this.$message.warning(this.$t('common.form.preview.materialVerifyEliminate.tip4'))
      }

      let copyData = []
      // 允许显示被替换的物料 
      if(this.showReplacedMaterialCheck){
        tableData = tableData.map(item=>{
          item.replacedMaterial = {
            name:item.name || item.materialName,
            materialName:item.name || item.materialName,
            materialSn:item.materialSn || item.sn,
            label:item.materialName,
            value:item.materialId,
            materialId:item.materialId,
            id:item.materialId,
            warrantyStatus:item.warrantyStatus,
            snManage:item.snManage,
            image:item.image,
            images:item.images,
            property:item.property || item.materialProperty,
            unit:item.unit || item.materialUnit,
            salePrice:item.salePrice || 0, 
            salePriceCurrency:item.salePriceCurrency || 'CNY', 
            num:1,
            isReplaced:true,
            selectBy:this.type,
          }
          return item
        })
        tableData.forEach(item => {
          if(item.number){
            for(let i = 0; i < item.number; i++){
              let obj = {
                ...item,
                number:1,
              }
              copyData.push(obj)
            }
          }
        })
      }else{
        // 如果是SN管理的
        tableData.forEach(item => {
          // TODO 国际化待办
          if(item.snManage === '是'){
            if(item.number){
              for(let i = 0; i < item.number; i++){
                let obj = {
                  ...item,
                  number:1,
                }
                copyData.push(obj)
              }
            }
            // 处理批次号并且没有sn的情况
          } else if(item.batchNumManage === 1 || item.batchNumManage === '是') {
            if(item.number){
              // 历史处理过的数量
              // let pushedNum = 0 
              let applyNum = item.number
              // 根据后端的的批次号列表循环
              for(let i = 0; i < (item?.materialRelationList || []).length; i++){
                const batchOrSnItem = item.materialRelationList[i] 
                applyNum -= batchOrSnItem.num
                // 判断总加的数量是否满足自己输入的数量
               
                let obj = {
                  ...item,
                  number: applyNum >= 0 ? batchOrSnItem.num : applyNum + batchOrSnItem.num,
                }
                copyData.push(obj)
              
                
                if(applyNum <= 0) break
              }
            }
          } else{
            copyData.push(item)  
          }
        })
      }

      this.$emit('input', {
        data:copyData,
        refsName: 'materialListDialog'
      })
    },
    getTableData() {
      return this.$refs?.materialTableNewVersion?.multipleSelection || []
    },
    close() {
      this.visible = false
      this.reset()
    },
    reset() {
      this.initForm()
    },
    initForm() {
      this.disabled = false
    }
  },
  components: {
    [MaterialTableNewVersion.name]: MaterialTableNewVersion
  }
}
</script>

<style lang="scss" scoped>
.material-list-dialog-container {
  ::v-deep .base-modal-body {
    padding: 16px 0 !important;
  }
}
.search-box , .table-box {
  padding:10px;
}
.search-box {
  width: 50%;
}
.paging-box{
  text-align: right;
}
</style>